<template>
  <QfPage title="公司管理">
    <template #hd>
      <el-row>
        <el-col :span="5">
          <el-button @click="showAddDialog = true"> 新增</el-button>
        </el-col>
        <el-col :span="4" :offset="1"> 是否只看vue <el-switch v-model="isVue" /> </el-col>
        <el-col :span="4" :offset="1"> 是否只看React <el-switch v-model="isReact" /> </el-col>
      </el-row>
    </template>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="公司id" width="180" />
      <el-table-column prop="name" label="公司名称" width="180" />
      <el-table-column prop="areaid" label="公司所在区域">
        <template #default="{ row }">
          {{ formatArea(row.areaid) }}
        </template>
      </el-table-column>
      <el-table-column prop="isVue" label="是否使用vue">
        <template #default="scope">
          {{ scope.row.isVue ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column prop="isReact" label="是否使用React">
        <template #default="scope">
          {{ scope.row.isReact ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column>
        <template #default="{ row }">
          <el-button type="danger" plain @click="handleDelete(row.id)"> 删除 </el-button>
          <el-button type="primary" plain @click="handleEditOpen(row)"> 编辑 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #ft>
      <el-pagination
        small
        background
        layout="prev, pager, next,sizes"
        :total="total"
        class="mt-4"
        :page-sizes="[5, 10, 30, 50]"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </template>
    <!--  添加弹窗  -->
    <el-dialog v-model="showAddDialog" title="添加公司信息" width="600px" center>
      <el-form :model="companyInfo" ref="addForm" label-width="100px">
        <el-form-item label="公司名称">
          <el-input v-model="companyInfo.name" />
        </el-form-item>
        <el-form-item label="公司所在区域">
          <el-cascader v-model="companyInfo.areaid" :options="regionDataPlus" />
        </el-form-item>
        <el-form-item label="使用vue">
          <el-switch v-model="companyInfo.isVue" />
        </el-form-item>
        <el-form-item label="使用React">
          <el-switch v-model="companyInfo.isReact" />
        </el-form-item>
        <el-form-item label="其他要求技能">
          <el-input
            type="textarea"
            :rows="4"
            :autosize="{ minRows: 4, maxRows: 4 }"
            v-model="companyInfo.skill"
          />
        </el-form-item>
        <el-form-item label="公司描述">
          <el-input
            type="textarea"
            :rows="4"
            :autosize="{ minRows: 4, maxRows: 4 }"
            v-model="companyInfo.desc"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="confirm">添加</el-button>
      </template>
    </el-dialog>
    <!-- 编辑抽屉 -->
    <el-drawer v-model="showEdit" title="编辑公司信息">
      <el-form :model="companyInfo" ref="addForm" label-width="100px">
        <el-form-item label="公司名称">
          <el-input v-model="companyInfo.name" />
        </el-form-item>
        <el-form-item label="公司所在区域">
          <el-cascader v-model="companyInfo.areaid" :options="regionDataPlus" />
        </el-form-item>
        <el-form-item label="使用vue">
          <el-switch v-model="companyInfo.isVue" />
        </el-form-item>
        <el-form-item label="使用React">
          <el-switch v-model="companyInfo.isReact" />
        </el-form-item>
        <el-form-item label="其他要求技能">
          <el-input
            type="textarea"
            :rows="4"
            :autosize="{ minRows: 4, maxRows: 4 }"
            v-model="companyInfo.skill"
          />
        </el-form-item>
        <el-form-item label="公司描述">
          <el-input
            type="textarea"
            :rows="4"
            :autosize="{ minRows: 4, maxRows: 4 }"
            v-model="companyInfo.desc"
          />
        </el-form-item>
      </el-form>
      <el-button @click="confirmEdit"> 确认修改 </el-button>
    </el-drawer>
  </QfPage>
</template>

<script>
import { regionDataPlus } from 'element-china-area-data';
import { ElMessageBox, ElNotification } from 'element-plus';
import {
  addCompany, getCompanyList, delCompany, editCompany,
} from '@/api/company';
import { showMsg } from '@/util/toast';

export default {
  name: 'companyPage',
  data() {
    return {
      showEdit: false,
      total: 0, // 分页需要使用的数据总数
      limit: 5, // 单页的数量
      curPage: 1, // 当前的页码
      regionDataPlus,
      isReact: false,
      isVue: false,
      companyInfo: {
        name: '',
        isVue: false,
        isReact: false,
        skill: '',
        desc: '',
        areaid: '',
      },
      id: 1,
      showAddDialog: false,
      tableData: [],
      curCompanyId: '',
    };
  },
  watch: {
    isVue() {
      this.getList();
    },
    isReact() {
      this.getList();
    },
    $route(nv) {
      console.log('通过watch来监听最新的路由信息', nv);
    },
  },
  created() {
    console.log('公司组件 created', regionDataPlus);
    this.getList(); // 组件创建完成之后执行一个获取列表的操作
    this.$router.push('/list');
  },
  methods: {
    handleEditOpen(row) {
      const {
        id, isReact, isVue, areaid, ...info
      } = row;
      this.curCompanyId = id;
      this.companyInfo = {
        ...info,
        isReact: isReact === 1 ? true : false,
        isVue: isVue === 1 ? true : false,
        areaid: areaid.split(','),
      };

      this.showEdit = true;
    },
    handleDelete(id) {
      console.log('要删除的id', id);
      // 让用户确认删除
      ElMessageBox.confirm('该操作无法撤回请问是否继续删除?', '请确认', {
        confirmButtonText: '没错！',
        cancelButtonText: '算了',
        type: 'warning',
      })
        .then(async () => {
          console.log('确认');
          const res = await delCompany(id);
          console.log('删除的结果', res);
          const { statusText } = res;
          if (statusText === 'OK') {
            ElNotification({
              title: '成功',
              message: '该信息删除成功',
              type: 'success',
            });
            return this.getList();
          }
          showMsg('删除失败');
        })
        .catch(() => {
          console.log('取消');
        });
    },
    handlePageChange(res) {
      console.log('页面发生了变化', res);
      this.curPage = res;
      this.getList();
    },
    handleSizeChange(res) {
      console.log('每页条数发生变化', res);
      this.limit = res;
      this.getList();
    },
    gogogo() {
      this.id += 1;
      // 我们跳转的是同一个页面的路由 唯独是参数发生了变化 但是再次执行的时候
      // created mounted 就不会触发了？？
      this.$router.push({ name: 'company', query: { id: this.id } });
    },
    formatArea(str) {
      const arr = str.split(',');
      // 省一级
      const province = regionDataPlus.find((item) => item.value === arr[0]);
      // 市一级
      const city = province.children.find((item) => item.value === arr[1]);
      // 区一级
      const zone = city.children.find((item) => item.value === arr[2]);
      return `${province.label}/${city.label}/${zone.label}`;
    },
    // 获取列表信息
    async getList() {
      const res = await getCompanyList({
        $limit: this.limit,
        $skip: (this.curPage - 1) * this.limit,
        isReact: this.isReact,
        isVue: this.isVue,
      });
      console.log('公司列表', res);
      const { statusText, data } = res;
      if (statusText !== 'OK') return showMsg('获取列表失败');
      this.tableData = data.data; // 给表格数据赋值
      this.total = data.total; // 总数据
    },
    async confirm() {
      console.log('公司的信息', this.companyInfo);
      const res = await addCompany({
        ...this.companyInfo,
        isReact: this.companyInfo.isReact ? 1 : 0,
        isVue: this.companyInfo.isVue ? 1 : 0,
        areaid: this.companyInfo.areaid.join(),
      });

      const { status } = res;
      console.log('status', status);
      if (status !== 201) return showMsg('添加失败');
      console.log('point fired', this.$refs.addForm);
      // 添加成功之后可以直接重新获取一下数据
      this.getList();
      // todo idn why running wrong
      this.$refs.addForm.resetFields();
      this.companyInfo = {
        name: '',
        isVue: false,
        isReact: false,
        skill: '',
        desc: '',
        areaid: '',
      };
      this.showAddDialog = false; // 关闭弹窗

      console.log('res', res);
    },
    async confirmEdit() {
      // 执行修改
      const res = await editCompany(
        {
          ...this.companyInfo,
          isReact: this.companyInfo.isReact ? 1 : 0,
          isVue: this.companyInfo.isVue ? 1 : 0,
          areaid: this.companyInfo.areaid.join(),
        },
        this.curCompanyId,
      );

      const { status } = res;
      console.log('status', status);
      if (status !== 200) return showMsg('修改失败');
      console.log('point fired', this.$refs.addForm);
      // 添加成功之后可以直接重新获取一下数据
      this.getList();
      // todo idn why running wrong
      this.$refs.addForm.resetFields();
      this.companyInfo = {
        name: '',
        isVue: false,
        isReact: false,
        skill: '',
        desc: '',
        areaid: '',
      };
      this.showEdit = false; // 关闭弹窗
    },
  },
  beforeRouteUpdate(to, from, next) {
    // 组件的内置钩子 发生在路由信息变化之前
    // 使用的场景就是需要监听路由参数的变化而路由的路径并没有发改变的时候
    console.log('通过 beforeRouteUpdate 来监听路由信息的变化', to);
    next();
  },
  beforeRouteEnter(to, from, next) {
    // 组件的内置钩子 进入之前
    console.log('有人打算进入公司管理');
    next(); // 以是否执行next 来表示是否能正常进入
  },
  beforeRouteLeave(to, from, next) {
    // 组件的内置钩子 离开之前
    const { path } = to;
    if (path !== '/qa') next();
  },
};
</script>

<style scoped></style>
